package com.hwy.widget.segment

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF

/**
 * =======================================
 * 作者: hewenyu
 * 日期: 2022/5/4 14:29
 * 说明: 底部指示器
 * =======================================
 */
class SegmentSliderIndicator(var width: Int, var height: Int, segment: TabSegment) :
    AbstractSegmentSlider(segment) {

    private val sliderPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            style = Paint.Style.FILL_AND_STROKE
        }
    }

    /**
     * 滑块绘制的区域
     */
    private val sliderRect by lazy {
        RectF()
    }

    override fun draw(currentIndex: Int, canvas: Canvas) {
        sliderPaint.color = segment.getSliderColor()
        if (isAnimatorRunning()) {
            // 绘制动画过程
            drawRunningSlider(canvas)
        } else {
            // 绘制静态指示器
            segment.getRectByIndex(currentIndex)?.run {
                val centerX = left + width() / 2F
                sliderRect.set(
                    centerX - width / 2F,
                    bottom - height.toFloat(),
                    centerX + width / 2F,
                    bottom.toFloat()
                )
                val corner = segment.getSliderCorner()
                canvas.drawRoundRect(sliderRect, corner, corner, sliderPaint)
            }
        }
    }

    private fun drawRunningSlider(canvas: Canvas) {
        segment?.let {
            it.getRectByIndex(fromIndex)?.let { fromRect ->
                it.getRectByIndex(toIndex)?.let { toRect ->
                    val fromCenterX = fromRect.left + fromRect.width() / 2F
                    val toCenterX = toRect.left + toRect.width() / 2F
                    // 取两个矩形的中心位置的横向差值
                    val distance = (toCenterX - fromCenterX) * fraction
                    sliderRect.set(
                        fromCenterX + distance - width / 2F,
                        fromRect.bottom - height.toFloat(),
                        fromCenterX + distance + width / 2F,
                        fromRect.bottom.toFloat()
                    )

                    val corner = segment.getSliderCorner()
                    canvas.drawRoundRect(sliderRect, corner, corner, sliderPaint)
                }
            }
        }
    }

}